/**
 *
 * @author ilya portnyagin iportnyagin@gmail.com
 */

package ru.portnyagin.helpdeskru.controller.admin;

import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import ru.portnyagin.helpdeskru.model.Organization;
import ru.portnyagin.helpdeskru.service.OrganizationService;
import ru.portnyagin.helpdeskru.util.JsfUtil;

@ManagedBean(name = "organizationController")
@ViewScoped
public class AdminOrganizationController implements Serializable {

    @EJB
    private ru.portnyagin.helpdeskru.service.OrganizationService organizationService;

    private List<Organization> listAllOrganization = null;
    private Organization currentOrg = null;
            
    public AdminOrganizationController() {
    }
    
    private OrganizationService getOrganizationService() {
        return organizationService;
    }

    public List<Organization> getListAllOrganization() {
        if(listAllOrganization == null) {
            listAllOrganization = getOrganizationService().findAll();
        }
        return listAllOrganization;
    }

    public Organization getCurrentOrg() {
        return currentOrg;
    }

    public void setCurrentOrg(Organization currentOrg) {
        this.currentOrg = currentOrg;
    }
    
    public void deleteOrg() {
        getOrganizationService().remove(currentOrg);
    }
    
    public void addNewOrg() {
        listAllOrganization.add(0, new Organization());
    }
    
    public void saveAll() {
        try{
            for(Organization o: listAllOrganization) {
                if(o.getId() != null) {
                    getOrganizationService().edit(o);
                } else {
                    getOrganizationService().create(o);
                }
            }
        } catch (Exception e){
            JsfUtil.addErrorMessage(e.toString());
        }

    }
    
    public SelectItem[] getSelectItemListOrganization() {
        return JsfUtil.getSelectItems(this.getListAllOrganization() , true);
    }
    

}
